<script setup>
// 爆款文案库
import { reactive, onMounted, ref, computed, watch } from "vue";
import { columns } from "./index.js";
// 处理总互动数
import { formatSum } from "@/views/shotstack/utils";
import request from "@/common/utils/request";
// import viewVideo from "@/views/shotstack/components/dialogComponent/ViewVideo.vue";
import viewVideo from "../../../../../views/shotstack/components/dialogComponent/viewVideo.vue";
import { useRoute, useRouter } from "vue-router";
import { nanoid } from "nanoid";
import {
  EyeOutlined,
  QuestionCircleOutlined,
  EllipsisOutlined,
} from "@ant-design/icons-vue";
import store from "@/store/index.js";

// 工具引入
import utils from "@/common/utils/utils.js";
import { message, notification } from "ant-design-vue";
const route = useRoute();
const router = useRouter();
const emit = defineEmits(["importUse:item"]);

// 充值弹窗
import vipModal from '@/socialMedia/Vip/vipModal.vue'
const vipVisible = ref(false)

// 筛选条件
const props = defineProps({
  startTime: {
    type: String,
    default: () => {
      return "";
    },
  },
  endTime: {
    type: String,
    default: () => {
      return "";
    },
  },
  tag_ids: {
    type: String,
    default: () => {
      return "";
    },
  },
  text: {
    type: String,
    default: () => {
      return "";
    },
  },
  filter_collect: {
    type: String,
    default: () => {
      return "";
    },
  },
  // 是否开启勾选模式
  isSelect: {
    type: Boolean,
    default: false,
  },
  // 勾选模式, 单选或者多选
  selectType: {
    type: String,
    default: "checkbox",
  },
});

const state = reactive({
  list: [],
  page: 1,
  pageSize: 10,
  total: 0,
  viewTextvisible: false,
  textUrl: "",
  orderBys: {
    publish_time: "",
  }, //是否开启排序
  selectedRowKeys: [],
  // table 展示的项, 在onMounted 中处理赋值
  columns: [],
});
const viewVideoRef = ref(null);
onMounted(() => {
  // 开启勾选状态, 仅保留需要的项
  if (props.isSelect) {
    const need = ["material_url", "edit"];
    state.columns = columns.filter((ele) => {
      return need.includes(ele.dataIndex);
    });
  } else {
    state.columns = JSON.parse(JSON.stringify(columns));
  }
  getExplosiveTextList();
});
// 获取爆款文案库列表
const getExplosiveTextList = async (ranking_type) => {
  const params = {
    tag_ids: props.tag_ids,
    startTime: props.startTime,
    endTime: props.endTime,
    text: props.text,
    page: state.page,
    pageSize: state.pageSize,
    filter_collect: props.filter_collect,
    orderBys: !!state.orderBys.publish_time ? state.orderBys : {},
    ranking_type: ranking_type ? ranking_type : 101,
  };
  const res = await request.get(
    "work_ai",
    "/user/shotstack/inspirationText/list",
    params
  );
  console.log(res, "我的灵感库");
  state.total = res.result.total;
  state.list = res.result.data;
};

const tabChange = (page, pageSize, sorter) => {
  // sorter : ascend: 升序, descend:降序, undefined:无排序
  console.log(page, pageSize, sorter, "页面改变");
  state.page = page.current;
  state.pageSize = page.pageSize;
  // 排序
  if (sorter.order == "ascend") {
    state.orderBys.publish_time = "asc";
  } else if (sorter.order == "descend") {
    state.orderBys.publish_time = "desc";
  } else {
    state.orderBys.publish_time = "";
  }

  getExplosiveTextList();
};

// table 勾选函数
const onSelectChange = (selectedRowKeys) => {
  console.log("selectedRowKeys changed: ", selectedRowKeys);
  state.selectedRowKeys = selectedRowKeys;
};

// 使用
const isUse = async (record) => {
  if (store.getters.isVersionExpired) {
    notification.warn({ message: "您的套餐已到期", duration: 2 });
    vipVisible.value = true
  } else {
    if (record.ai_to_tip != "") {
      message.warning(record.ai_to_tip);
      return;
    }
    const unique_id = nanoid();
    router.push(
      `/mixedCutCreat?id=${record.id}&key=id&viewType=2&openType=creat&isAi=true&unique_id=${unique_id}`
    );
  }
};

// 处理收藏
const collect = async (data) => {
  if (store.getters.isVersionExpired) {
    notification.warn({ message: "您的套餐已到期", duration: 2 });
    vipVisible.value = true
  } else {
    const res = await request.post(
      "work_ai",
      "/user/shotstack/inspirationText/collect",
      data
    );
    console.log(res, "收藏结果");
    getExplosiveTextList();
  }
};

const resetPage = () => {
  state.page = 1;
};
const viewText = (text) => {
  state.viewTextvisible = true;
  state.textUrl = text;
};
const copyText = (url) => {
  utils.copyText(url);
  state.viewTextvisible = false;
  ExplosiveText;
};
watch(
  props.ranking_type, // 要监听的响应式数据
  (newValue, oldValue) => {
    getExplosiveTextList();
  },
  {
    immediate: true, // 是否在初始加载时立即执行回调函数，默认为 false
    deep: false, // 是否深度监听嵌套对象的变化，默认为 false
  }
);

// 获得勾选项
const getSelects = () => {
  const list = state.list.filter((ele) => {
    return state.selectedRowKeys.includes(ele.id);
  });
  console.log(list, "选择的项");
  return list;
};

// 导入该项文案 -- 仅文案导入才会使用
const importUse = (item) => {
  emit("importUse", item);
};

defineExpose({
  getExplosiveTextList,
  resetPage,
  getSelects,
});
</script>

<template>
  <div class="ExplosiveText">
    <a-table :columns="state.columns" :data-source="state.list" @change="tabChange" :pagination="{
        pageSize: state.pageSize,
        current: state.page,
        total: state.total,
        showSizeChanger: false,
        showQuickJumper: true,
      }" :row-selection="
        props.isSelect
          ? {
              selectedRowKeys: state.selectedRowKeys,
              onChange: onSelectChange,
              type: props.selectType,
            }
          : null
      " :rowKey="props.isSelect ? 'id' : null">
      <template #headerCell="{ column }">
        <!-- 热度值 -->
        <template v-if="column.key == 'score_text'">
          <span> {{ column.title }} </span>
          <a-tooltip>
            <template #title>根据时间周期内新增的播放、点赞、评论、分享等指标加权计算
            </template>
            <question-circle-outlined style="margin-left: 3px" />
          </a-tooltip>
        </template>
        <!-- 新增粉丝量 -->
        <template v-if="column.key == 'fans_text'">
          <span> {{ column.title }} </span>
          <a-tooltip>
            <template #title>时间周期内新增的粉丝量 </template>
            <question-circle-outlined style="margin-left: 3px" />
          </a-tooltip>
        </template>
        <!-- 新增点赞量 -->
        <template v-if="column.key == 'like_text'">
          <span> {{ column.title }} </span>
          <a-tooltip>
            <template #title>时间周期内新增的点赞量 </template>
            <question-circle-outlined style="margin-left: 3px" />
          </a-tooltip>
        </template>
        <!-- 新增播放量 -->
        <template v-if="column.key == 'play_text'">
          <span> {{ column.title }} </span>
          <a-tooltip>
            <template #title>时间周期内新增的播放量 </template>
            <question-circle-outlined style="margin-left: 3px" />
          </a-tooltip>
        </template>
        <!-- 涨粉率 -->
        <template v-if="column.key == 'follow_rate_text'">
          <span> {{ column.title }} </span>
          <a-tooltip>
            <template #title>新增粉丝量/新增播放量 </template>
            <question-circle-outlined style="margin-left: 3px" />
          </a-tooltip>
        </template>
        <!-- 点赞率 -->
        <template v-if="column.key == 'like_rate_text'">
          <span> {{ column.title }} </span>
          <a-tooltip>
            <template #title>新增点赞量/新增播放量 </template>
            <question-circle-outlined style="margin-left: 3px" />
          </a-tooltip>
        </template>
      </template>
      <template #bodyCell="{ column, record }">
        <!-- 达人信息 -->
        <template v-if="column.key === 'text'">
          <div class="user_msg">
            <div class="user_msg_left">
              <img :src="record.avatar" alt="" />
            </div>
            <div class="user_msg_right">
              <span class="name">{{ record.author }}</span>
              <span>{{ record.publish_time || "--" }}</span>
            </div>
          </div>
        </template>
        <!-- 排行 -->
        <template v-if="column.key === 'rank_value'">
          <div class="rank_value_box">
            <!-- <img v-if="record.rank_value == 1" src="./topOne.png" alt=""> -->
            <img v-if="record.rank_value == 1" :src="utils.staticPath + 'images/workAi/shotstack/topOne.png'" alt="" />
            <img v-else-if="record.rank_value == 2" :src="utils.staticPath + 'images/workAi/shotstack/topTwo.png'"
              alt="" />
            <img v-else-if="record.rank_value == 3" :src="utils.staticPath + 'images/workAi/shotstack/topThree.png'"
              alt="" />
            <span v-else style="
                font-size: 20px;
                font-weight: bolder;
                color: #999;
                line-height: 20px;
              ">{{ record.rank_value }}</span>
          </div>
        </template>
        <template v-if="column.key === 'edit'">
          <template v-if="!props.isSelect">
            <div class="edit_btns">
              <a-button @click="isUse(record)" size="small">图生视频</a-button>
              <a-button @click="
                  collect({
                    inspiration_text_id: record.id,
                    operation: 'collection',
                  })
                " v-if="!record.my_collect" size="small">收藏</a-button>
              <a-button @click="
                  collect({
                    inspiration_text_id: record.id,
                    operation: 'cancel',
                  })
                " v-else size="small">取消收藏</a-button>
            </div>
          </template>
          <template v-else>
            <div class="edit_btns">
              <a-button @click="importUse(record)" size="small" type="link">导入文案</a-button>
            </div>
          </template>
        </template>
        <!-- <template v-if="column.key === 'share_text'">
          <span>{{
            formatSum([
              +record.collect,
              +record.comment,
              +record.like,
              +record.share,
            ])
          }}</span>
        </template> -->
        <!-- 视频信息 -->
        <template v-if="column.key === 'material_url'">
          <a-popover title="视频名称">
            <template #content>
              <div class="video_title_text" style="max-width: 400px">
                {{ record?.title || "暂无标题" }}
              </div>
            </template>
            <div class="material_url_box" style="">
              <div class="video_box" v-if="record.material_url || record.cover_url">
                <img v-if="record.cover_url" :src="record.cover_url" alt="" @click="
                    record.material_url &&
                      viewVideoRef.open(record.material_url)
                  " style="height: 60px; width: 60px; object-fit: contain" />
                <video v-else :key="record.material_url" style="height: 60px; width: 60px" @click="
                    record.material_url &&
                      viewVideoRef.open(record.material_url)
                  ">
                  <source :src="record.material_url" type="video/mp4" />
                </video>
              </div>
              <div style="height: 60px; width: 60px; background: transparent" v-else>
                <!-- <a-spin>
              </a-spin> -->
              </div>

              <div class="text_item" :style="{ 'max-width': props.isSelect ? '' : '240px' }" style="text-align: left">
                <template v-if="props.isSelect">
                  <span>
                    {{ record?.text }}
                  </span>
                </template>

                <template v-else>
                  {{ record?.text?.slice(0, 30) || "暂无文案" }}
                  <span @click="viewText(record.text)" style="cursor: pointer"
                    v-if="record?.text?.trim().length > 30"><ellipsis-outlined /><eye-outlined
                      class="view_icon" /></span>
                </template>

                {{ record?.text?.slice(0, 30) || "暂无文案" }}

                <!-- </a-popover> -->
              </div>
            </div>
          </a-popover>
        </template>
      </template>
    </a-table>
  </div>

  <viewVideo ref="viewVideoRef"></viewVideo>
  <a-modal v-model:visible="state.viewTextvisible" title="文案预览" @cancel="viewTextvisible = false">
    <div class="view_text" style="max-height: 400px; overflow-y: auto">
      {{ state.textUrl }}
    </div>
    <template #footer>
      <a-button key="back" @click="state.viewTextvisible = false" style="border-radius: 5px">取消</a-button>
      <a-button key="submit" type="primary" @click="copyText(state.textUrl)" style="border-radius: 5px">复制全部</a-button>
    </template>
  </a-modal>

  <!-- 充值弹窗 -->
  <vipModal :visible="vipVisible" @close="vipVisible = false"></vipModal>

</template>

<style lang="less" scoped>
.ExplosiveText {
  .edit_btns {
    display: flex;
    gap: 10px;
    justify-content: center;
  }

  // 排行
  .rank_value_box {
    img {
      width: 30px;
      height: 30px;
    }
  }

  // 关联视频
  .material_url_box {
    width: 100%;
    // background: #000;
    display: flex;
    justify-content: space-between;
    gap: 15px;

    .video_box {
      background: #000;
      cursor: pointer;
    }

    .text_item {
      flex: 1;
      // max-width: 240px;

      .view_icon {
        margin-left: 10px;
      }
    }
  }

  .user_msg {
    width: 100%;
    display: flex;
    gap: 10px;
    justify-content: center;
    align-items: center;

    .user_msg_right {
      display: flex;
      flex-direction: column;

      .name {
        vertical-align: middle;
        max-width: 8em;
        /* 设置宽度以限制字符数量 */
        white-space: nowrap;
        /* 防止文本换行 */
        overflow: hidden;
        /* 隐藏溢出的文本部分 */
        text-overflow: ellipsis;
        /* 使用省略号表示溢出的文本 */
        text-align: start;
      }
    }

    .user_msg_left {
      display: flex;
      flex-direction: column;
      align-items: center;

      img {
        height: 30px;
        width: 30px;
        border-radius: 50%;
        overflow: hidden;
      }
    }
  }
}

.view_text::-webkit-scrollbar {
  display: none;
}

.video_title_text {
  max-height: 500px;
  overflow-y: auto;

  &::-webkit-scrollbar {
    width: 8px;
    /* 滚动条的宽度 */
    height: 10px;
    /* 滚动条的高度，垂直滚动条可能用得上 */
    // display: none;
  }

  &::-webkit-scrollbar-thumb {
    background: #888;
    /* 滑块的背景颜色 */
    border-radius: 10px;
    /* 滑块的圆角 */
  }
}
</style>
